package com.budwk.app.sqfw.controllers.admin;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.StrFormatter;
import com.budwk.app.oss.models.SysOss;
import com.budwk.app.oss.services.SysOssService;
import com.budwk.app.sqfw.dto.ServiceRecordPdfOrExcelCollDTO;
import com.budwk.app.sqfw.dto.SqfwServiceOrderUpdateDTO;
import com.budwk.app.sqfw.dto.SqfwServicerecordForAdminDTO;
import com.budwk.app.sqfw.dto.TransferServiceRecordDTO;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary;
import com.budwk.app.sqfw.models.Sqfw_servicerecord;
import com.budwk.app.sqfw.models.Sqfw_workorder;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.tencent.TCyysb;
import com.budwk.app.sqfw.vo.SqfwWorkOrderVO;
import com.budwk.app.sqfw.vo.UserServiceOrderVO;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysRoleService;
import com.budwk.app.sys.services.SysRoleUserService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.AudioToTextUtils;
import com.budwk.app.util.AuthorityUtil;
import com.budwk.starter.common.openapi.annotation.*;
import com.budwk.starter.common.page.PageUtil;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.log.annotation.SLog;
import com.budwk.starter.security.utils.SecurityUtil;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import fr.opensagres.poi.xwpf.converter.pdf.PdfConverter;
import fr.opensagres.poi.xwpf.converter.pdf.PdfOptions;
import jodd.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.mvc.annotation.*;
import org.slf4j.Logger;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

/**
 * @program: SqfwServicerecordForAdminController
 * @description: 任务记录（后台管理系统）
 * @author: LJT
 * @create: 2023-10-28 10:20
 **/
@IocBean
@At("/platform/sqfw/recordForAdmin")
@ApiDefinition(tag = "任务记录")
@Slf4j
public class SqfwServicerecordForAdminController {
    @Inject
    private SqfwServicerecordForAdminService sqfwServicerecordForAdminService;

    @Inject
    private SqfwServicerecordService sqfwServicerecordService;

    @Inject
    private SqfwWorkorderService sqfwWorkorderService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private SysRoleUserService sysRoleUserService;

    @Inject
    private SysRoleService sysRoleService;

    @Inject
    private HuaweiOssService huaweiOssService;

    @Inject
    private PropertiesProxy propertiesProxy;

    @Inject
    private SysOssService sysOssService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    private final ExecutorService executorService = Executors.newFixedThreadPool(50);

    private final String EOL = System.getProperty("line.separator");

    private Logger logger;

    @Inject
    Dao dao;

    @Inject
    private SqfwSummaryForAdminService sqfwSummaryForAdminService;

    @Inject
    private SqfwFormSummaryService sqfwFormSummaryService;


    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询通讯服务记录")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses(
            implementation = Sqfw_servicerecord.class
    )
    @SaCheckPermission("sqfw.servicerecord")
    @SLog(tag = "分页查询通讯服务记录")
    public Result<?> list(@Param("..") Sqfw_servicerecord bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy, @Param("workOrderFlag") Boolean workOrderFlag) {

        long startTime = System.currentTimeMillis();

        Cnd cnd = createListServiceRecordPermissionCnd(SecurityUtil.getUserId());
        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        } else {
            cnd.orderBy("createdat", "desc");
        }

        if (bean.getCustomer_name() != null && Strings.isNotBlank(bean.getCustomer_name().toString())) {
            cnd.and("customer_name", "like", "%" + bean.getCustomer_name() + "%");
        }

        if (bean.getFinishStatus() != null && Strings.isNotBlank(bean.getFinishStatus().toString())) {
            cnd.and("finish_status", "like", "%" + bean.getFinishStatus() + "%");
        }

        if (bean.getDuration() != null && Strings.isNotBlank(bean.getDuration().toString())) {
            cnd.and("duration", "like", "%" + bean.getDuration() + "%");
        }

        if (bean.getCustomer_phone() != null && Strings.isNotBlank(bean.getCustomer_phone().toString())) {
            cnd.and("customer_phone", "like", "%" + bean.getCustomer_phone() + "%");
        }

        if (bean.getCustomer_address() != null && Strings.isNotBlank(bean.getCustomer_address().toString())) {
            cnd.and("customer_address", "like", "%" + bean.getCustomer_address() + "%");
        }

        if (bean.getRecording_file() != null && Strings.isNotBlank(bean.getRecording_file().toString())) {
            cnd.and("recording_file", "like", "%" + bean.getRecording_file() + "%");
        }

        if (bean.getRecording_text() != null && Strings.isNotBlank(bean.getRecording_text().toString())) {
            cnd.and("recording_text", "like", "%" + bean.getRecording_text() + "%");
        }

        if (bean.getType() != null && Strings.isNotBlank(bean.getType().toString())) {
            cnd.and("type", "like", "%" + bean.getType() + "%");
        }

        if (bean.getConnect_time() != null && Strings.isNotBlank(bean.getConnect_time().toString())) {
            Instant instant = bean.getConnect_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("connect_time", "between", new Object[]{startdateStr, enddateStr});
        }

        if (bean.getEnd_time() != null && Strings.isNotBlank(bean.getEnd_time().toString())) {
            Instant instant = bean.getEnd_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("connect_time", "between", new Object[]{startdateStr, enddateStr});
        }

        if (bean.getCustomer_need() != null && Strings.isNotBlank(bean.getCustomer_need().toString())) {
            cnd.and("customer_need", "like", "%" + bean.getCustomer_need() + "%");
        }

        if (bean.getService_name() != null && Strings.isNotBlank(bean.getService_name().toString())) {
            cnd.and("service_name", "like", "%" + bean.getService_name() + "%");
        }

        if (bean.getService_phone() != null && Strings.isNotBlank(bean.getService_phone().toString())) {
            cnd.and("service_phone", "like", "%" + bean.getService_phone() + "%");
        }

        if (bean.getReceive_time() != null && Strings.isNotBlank(bean.getReceive_time().toString())) {
            Instant instant = bean.getReceive_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("receive_time", "between", new Object[]{startdateStr, enddateStr});
        }

        if (bean.getFinish_time() != null && Strings.isNotBlank(bean.getFinish_time().toString())) {
            Instant instant = bean.getFinish_time().toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();

            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String startdateStr = localDateTime.format(fmt);
            String enddateStr = localDateTime.plusDays(1).format(fmt);

            cnd.and("finish_time", "between", new Object[]{startdateStr, enddateStr});
        }

        if (bean.getCreatedAt() != null && Strings.isNotBlank(bean.getCreatedAt().toString())) {
            Long endDate = bean.getCreatedAt() + 86400000;
            cnd.and("createdat", "between", new Object[]{bean.getCreatedAt(), endDate});
        }

        if (bean.getHandle_result() != null && Strings.isNotBlank(bean.getHandle_result().toString())) {
            cnd.and("handle_result", "=", "%" + bean.getHandle_result() + "%");
        }

        if (bean.getHandle_detail() != null && Strings.isNotBlank(bean.getHandle_detail().toString())) {
            cnd.and("handle_detail", "like", "%" + bean.getHandle_detail() + "%");
        }

        if (bean.getHandle_detail() != null && Strings.isNotBlank(bean.getHandle_detail().toString())) {
            cnd.and("handle_detail", "like", "%" + bean.getHandle_detail() + "%");
        }

        if (bean.getCopyName() != null && Strings.isNotBlank(bean.getCopyName().toString())) {
            cnd.and("copy_name", "like", "%" + bean.getCopyName() + "%");
        }

        if (bean.getCopyPhone() != null && Strings.isNotBlank(bean.getCopyPhone().toString())) {
            cnd.and("copy_phone", "like", "%" + bean.getCopyPhone() + "%");
        }

        if (bean.getCompanyName() != null && Strings.isNotBlank(bean.getCompanyName().toString())) {
            cnd.and("company_name", "like", "%" + bean.getCompanyName() + "%");
        }

        if (bean.getCreatedBy() != null && Strings.isNotBlank(bean.getCreatedBy())) {
            cnd.and("createdby", "=", bean.getCreatedBy());
        }

        cnd.and("delflag", "=", false);

        Pagination pagination = sqfwServicerecordForAdminService.listPage(pageNo, pageSize, cnd);

        List<Sqfw_servicerecord> list = pagination.getList(Sqfw_servicerecord.class);

        // 如果需要查看相应的工单信息
        if (workOrderFlag != null && workOrderFlag) {
            CountDownLatch countDownLatch = new CountDownLatch(list.size());

            ConcurrentHashMap<String, UserServiceOrderVO> resultServiceOrderMap = new ConcurrentHashMap<>();
            for (Sqfw_servicerecord serviceRecord : list) {
                executorService.execute(() -> {
                    try {
                        UserServiceOrderVO resultVO = new UserServiceOrderVO();
                        BeanUtil.copyProperties(serviceRecord, resultVO);

                        // 根据sqfw_id 和 from_userid 查询相应的工单信息
                        List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("from_user_id", "=", serviceRecord.getCreatedBy()));
                        resultVO.setUserWorkOrderList(sqfwWorkorderService.getVO(workOrderList));

                        // 根据sqfw_id 和 user_id 查询该语音记录所对应的工单信息
                        List<Sqfw_workorder> curServiceOrderWorkOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("user_id", "=", serviceRecord.getCreatedBy()));
                        List<SqfwWorkOrderVO> curUserVOList = sqfwWorkorderService.getVO(curServiceOrderWorkOrderList);
                        if (curUserVOList.size() > 0) resultVO.setUserWorkOrder(curUserVOList.get(0));

                        List<Sqfw_workorder> workOrderOfRecordList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("from_user_id", "is not", null)
                                .and("delflag", "=", false));
                        int workOrderCompleteCount = 0;
                        int workOrderNotCompleteCount = 0;
                        for (Sqfw_workorder workOrderOfRecord : workOrderOfRecordList) {
                            String wk_status = workOrderOfRecord.getWk_status();
                            if (StringUtils.isNotBlank(wk_status) && wk_status.equals("complete"))
                                workOrderCompleteCount++;
                            else workOrderNotCompleteCount++;
                        }
                        String completeMsg = StrFormatter.format("完成{}人，未完成{}人", workOrderCompleteCount, workOrderNotCompleteCount);
                        resultVO.setHandle_result(completeMsg);


                        resultServiceOrderMap.put(resultVO.getId(), resultVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            }

            try {
                countDownLatch.await();
            } catch (Exception ignored) {
            }

            List<UserServiceOrderVO> resultList = Lists.newArrayList();
            for (Sqfw_servicerecord sqfw_servicerecord : list) {
                resultList.add(resultServiceOrderMap.get(sqfw_servicerecord.getId()));
            }
            pagination.setList(resultList);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("---------------" + (endTime - startTime));
        return Result.data(pagination);

    }

    /**
     * 任务记录管理列表查询（用于后台管理系统）
     * Add by LJT 2023-10-08
     */
    @At("/listForBM")
    @Ok("json")
    @POST
    @ApiOperation(name = "任务记录管理列表分页查询")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = SqfwServicerecordForAdminDTO.class
    )
    @ApiResponses(
            implementation = Sqfw_servicerecord.class
    )
    @SLog(tag = "任务记录管理列表分页查询")
    @SaCheckLogin
    public Result<?> listForBM(@Param("..") SqfwServicerecordForAdminDTO bean, @Param("pageNo") int pageNo, @Param("pageSize") int pageSize, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy, @Param("workOrderFlag") Boolean workOrderFlag) throws ParseException {
        long startTime = System.currentTimeMillis();
        // 用户查询权限
        AuthorityUtil.checkServicerecordAreaPermission(bean);
        Cnd cnd = this.getConditionList(bean);

        if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
            cnd.orderBy(pageOrderName, PageUtil.getOrder(pageOrderBy));
        } else {
            cnd.orderBy("createdat", "desc");
        }
        Pagination pagination = sqfwServicerecordForAdminService.listPage(pageNo, pageSize, cnd);
        List<Sqfw_servicerecord> tmplist = pagination.getList(Sqfw_servicerecord.class);
        // 任务记录中返回一个标识给前端判断是否有文件URL,通过流程表resource_path字段是否有url来判断
        List<Sqfw_servicerecord> list = new ArrayList<Sqfw_servicerecord>();
        for (Sqfw_servicerecord sqfwServicerecord : tmplist) {
            Cnd cndFlow = Cnd.NEW();
            cndFlow.and("sqfw_id", "=", sqfwServicerecord.getId());
            List<Sqfw_completeflow> sqfwCompleteflows = sqfwCompleteflowService.query(cndFlow);
            if (sqfwCompleteflows.size() > 0) {
                sqfwServicerecord.setDownFlag(true);
            }
            list.add(sqfwServicerecord);
        }

        // 如果需要查看相应的工单信息
        if (workOrderFlag != null && workOrderFlag) {
            CountDownLatch countDownLatch = new CountDownLatch(list.size());
            ConcurrentHashMap<String, UserServiceOrderVO> resultServiceOrderMap = new ConcurrentHashMap<>();
            for (Sqfw_servicerecord serviceRecord : list) {
                executorService.execute(() -> {
                    try {
                        UserServiceOrderVO resultVO = new UserServiceOrderVO();
                        BeanUtil.copyProperties(serviceRecord, resultVO);
                        // 根据sqfw_id 和 from_userid 查询相应的工单信息
                        List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("from_user_id", "=", serviceRecord.getCreatedBy()));
                        resultVO.setUserWorkOrderList(sqfwWorkorderService.getVO(workOrderList));

                        // 根据sqfw_id 和 user_id 查询该语音记录所对应的工单信息
                        List<Sqfw_workorder> curServiceOrderWorkOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("user_id", "=", serviceRecord.getCreatedBy()));
                        List<SqfwWorkOrderVO> curUserVOList = sqfwWorkorderService.getVO(curServiceOrderWorkOrderList);
                        if (curUserVOList.size() > 0) resultVO.setUserWorkOrder(curUserVOList.get(0));
                        List<Sqfw_workorder> workOrderOfRecordList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                                .and("from_user_id", "is not", null)
                                .and("delflag", "=", false));
                        int workOrderCompleteCount = 0;
                        int workOrderNotCompleteCount = 0;
                        for (Sqfw_workorder workOrderOfRecord : workOrderOfRecordList) {
                            String wk_status = workOrderOfRecord.getWk_status();
                            if (StringUtils.isNotBlank(wk_status) && wk_status.equals("complete"))
                                workOrderCompleteCount++;
                            else workOrderNotCompleteCount++;
                        }
                        String completeMsg = StrFormatter.format("完成{}人，未完成{}人", workOrderCompleteCount, workOrderNotCompleteCount);
                        resultVO.setHandle_result(completeMsg);
                        resultServiceOrderMap.put(resultVO.getId(), resultVO);
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        countDownLatch.countDown();
                    }
                });
            }

            try {
                countDownLatch.await();
            } catch (Exception ignored) {
            }

            List<UserServiceOrderVO> resultList = Lists.newArrayList();
            for (Sqfw_servicerecord sqfw_servicerecord : list) {
                resultList.add(resultServiceOrderMap.get(sqfw_servicerecord.getId()));
            }
            //pagination.setTotalCount(resultList.size());
            pagination.setList(resultList);
        }

        long endTime = System.currentTimeMillis();
        System.out.println("---------------" + (endTime - startTime));
        return Result.data(pagination);

    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "新增通讯服务记录")
    @ApiFormParams(
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses
    @SLog(tag = "新增通讯服务记录", value = "${args[0].id}")
    @SaCheckPermission("sqfw.servicerecord.create")
    public Result<?> create(@Param("..") Sqfw_servicerecord sqfwServicerecord, HttpServletRequest req) {
        sqfwServicerecord.setCreatedBy(SecurityUtil.getUserId());
        String getPhone = sqfwServicerecord.getService_phone();
        if (StringUtils.isNotBlank(sqfwServicerecord.getRecording_file())
                && !sqfwServicerecord.getApp_type().equals("7")
                && !sqfwServicerecord.getApp_type().equals("8")) {
            String url = huaweiOssService.getPwdPath(sqfwServicerecord.getRecording_file());

            String serviceIp = propertiesProxy.get("jarService.ip");
            String port = propertiesProxy.get("server.port");
            String callback = StrFormatter.format("http://{}:{}/platform/sqfw/cloudcallback/callback", serviceIp, port);
            Long taskId = TCyysb.Send(url, callback);
            System.out.println("新增通讯服务记录: ");
            System.out.println(taskId);
            System.out.println(sqfwServicerecord);

            if (taskId != null && taskId > 0L) {
                sqfwServicerecord.setTaskId(taskId.toString());
            }
        }
        sqfwServicerecord.setDelFlag(false);
        if (!StringUtils.isNotBlank(sqfwServicerecord.getService_phone()) && sqfwServicerecord.getDuration() != null) {
            Long shichang = sqfwServicerecord.getDuration() / 1000;
            sqfwServicerecord.setDuration(shichang);
            Date endtime = new Date(sqfwServicerecord.getConnect_time().getTime() + shichang);
            sqfwServicerecord.setEnd_time(endtime);
        }
        sqfwServicerecord.setRecording_text(sqfwServicerecord.getRecording_text());
        //消息转发后自动会填
        sqfwServicerecord.setService_phone(null);
        sqfwServicerecord.setService_name(null);
        sqfwServicerecord.setFinishStatus("new");
        Sqfw_servicerecord newServiceOrder = sqfwServicerecordForAdminService.insert(sqfwServicerecord);
        Result result = Result.NEW();
        result.addData(sqfwServicerecord.getId());

        //if (sqfwServicerecord.getService_phone()==null){
        //}
        // 新增语音通话需要生成一个工单
        Sqfw_workorder workOrder = new Sqfw_workorder();
        workOrder.setSqfw_id(newServiceOrder.getId());
        if (StringUtils.isNotBlank(newServiceOrder.getCreatedBy())) {
            Sys_user sysUser = sysUserService.fetch(newServiceOrder.getCreatedBy());
            if (sysUser != null) workOrder.setUser_name(sysUser.getUsername());
        }
        workOrder.setWk_grade("0");
        workOrder.setWk_priority("take_time_complete");
        workOrder.setUser_id(newServiceOrder.getCreatedBy());
        workOrder.setCreateDate(new Date());
        workOrder.setUpdatedAt(new Date());
        workOrder.setCreatedBy(newServiceOrder.getCreatedBy());
        // wzy 2023-5-25 服务记录生成工单的时候不主动完成对应工单
        workOrder.setWk_status("new");
        // workOrder.setComplete_time(new Date());
        workOrder.setDelflag(false);
        workOrder.setServiceType(sqfwServicerecord.getType());
        sqfwWorkorderService.insert(workOrder);

        if (StringUtils.isNotBlank(getPhone)) {
            List<String> strings = new ArrayList<>();
            TransferServiceRecordDTO dto = new TransferServiceRecordDTO();
            dto.setServiceRecordId(newServiceOrder.getId());
            List<String> list = Lists.newArrayList(getPhone.split(","));
            for (String str : list) {
                Sys_user sysUser = sysUserService.getUserByLoginname(str);
                strings.add(sysUser.getId());
            }
            dto.setToSysUserIdList(strings);
            sqfwWorkorderService.transferServiceRecordNew(dto);
        }

        return result;
    }

    @At("/updateTransmit")
    @Ok("json")
    @POST
    @ApiOperation(name = "修改转发")
    @ApiFormParams(
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses
    @SLog(tag = "修改转发", value = "${id}")
    // @SaCheckPermission("sqfw.servicerecord.update")
    public Result<?> updateTransmit(@Param("id") String id, @Param("service_phone") String service_phone, @Param("wk_priority") String wk_priority) {
        List<String> strings = new ArrayList<>();
        TransferServiceRecordDTO dto = new TransferServiceRecordDTO();
        dto.setServiceRecordId(id);
        List<String> list = Lists.newArrayList(service_phone.split(","));
        for (String str : list) {
            Sys_user sysUser = sysUserService.getUserByLoginname(str);
            strings.add(sysUser.getId());
        }
        dto.setToSysUserIdList(strings);
        dto.setWorkOrderWkPriority(wk_priority);
        sqfwWorkorderService.transferServiceRecordNew(dto);

        return Result.success();
    }

    @At
    @Ok("json")
    @POST
    @ApiOperation(name = "修改通讯服务记录")
    @ApiFormParams(
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses
    @SLog(tag = "修改通讯服务记录", value = "${args[0]}")
    // @SaCheckPermission("sqfw.servicerecord.update")
    public Result<?> update(@Param("..") SqfwServiceOrderUpdateDTO sqfwServicerecord, HttpServletRequest req) {

        String finishStatus = sqfwServicerecord.getFinishStatus();
        if (StringUtils.isNotBlank(finishStatus) && finishStatus.equals("complete")) {
            String sqfwServicerecordId = sqfwServicerecord.getId();
            Sqfw_servicerecord existServiceOrder = sqfwServicerecordForAdminService.fetch(sqfwServicerecordId);
            if (StringUtils.isBlank(existServiceOrder.getFinishStatus()) || !existServiceOrder.getFinishStatus().equals("complete")) {
                sqfwServicerecord.setFinish_time(new Date());
            }
        }
        sqfwServicerecord.setUpdatedBy(SecurityUtil.getUserId());
        sqfwServicerecordForAdminService.updateIgnoreNull(sqfwServicerecord);
        return Result.success();
    }

    @At("/get")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取通讯服务记录")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SaCheckPermission("sqfw.servicerecord")
    @SLog(tag = "根据id获取通讯服务记录,id:{$id}")
    public Result<?> getData(@Param("id") String id, HttpServletRequest req) {
        if (StringUtils.isBlank(id)) return Result.error("id不能为空");
        List<String> idList = new ArrayList<>();
        idList.add(id);
        List<UserServiceOrderVO> list = sqfwServicerecordForAdminService.listByServiceOrderIdList(idList);
        Sqfw_servicerecord sqfwServiceRecord = list.get(0);

        // 需要把所有时间去掉
        String newContent = AudioToTextUtils.replaceMsgContentNotPrefix(sqfwServiceRecord.getRecording_text());
        sqfwServiceRecord.setRecording_text(newContent);

        String serviceRecordId = sqfwServiceRecord.getId();
        String createdBy = sqfwServiceRecord.getCreatedBy();
        List<Sqfw_workorder> workOrderList = sqfwWorkorderService.queryBySqfwIdAndFromUserId(serviceRecordId, createdBy);
        Set<String> userIdSet = workOrderList.stream().map(Sqfw_workorder::getUser_id).collect(Collectors.toSet());
        List<Sys_user> userList = sysUserService.getUserByIds(userIdSet);

        List<String> userNameList = new ArrayList<>();
        List<String> userPhoneList = new ArrayList<>();
        for (Sys_user sys_user : userList) {
            userNameList.add(sys_user.getUsername());
            userPhoneList.add(sys_user.getMobile());
        }

        if (userNameList.size() > 0) sqfwServiceRecord.setService_name(Joiner.on(",").join(userNameList));
        if (userPhoneList.size() > 0) sqfwServiceRecord.setService_phone(Joiner.on(",").join(userPhoneList));


        return Result.success(sqfwServiceRecord);
    }

    @At("/delete")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除通讯服务记录")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "id", description = "唯一标识", required = true, check = true)
            }
    )
    @SLog(tag = "删除通讯服务记录", value = "${args[0]}")
    @SaCheckPermission("sqfw.servicerecord.delete")
    public Result<?> delete(@Param("id") String id, HttpServletRequest req) {
        Sqfw_servicerecord sqfwServicerecord = sqfwServicerecordForAdminService.fetch(id);
        if (sqfwServicerecord == null) {
            return Result.error(ResultCode.NULL_DATA_ERROR);
        }
        sqfwServicerecordForAdminService.delete(id);
        req.setAttribute("_slog_msg", sqfwServicerecord.getId());
        return Result.success();
    }


    /**
     * 将word中某些标签替换成指定的值，并生成一个新的word文档。
     *
     * @throws IOException
     */
    @At("/insertAndOutFile")
    @Ok("json")
    @POST
    @ApiOperation(name = "word插入数据")
    @ApiFormParams()
    @SLog(tag = "word插入数据", value = "${args[0]},${args[1]},${args[2]}")
    @SaCheckPermission("sqfw.servicerecord.insertAndOutFile")
    public Result insertAndOutFile2(@Param("type") String type, @Param("startTime") String startTime, @Param("endTime") String endTime) {
        Result result = Result.NEW();
        Map<String, String> map = new HashMap<>();
        String pdf = "";
        String templateFile = propertiesProxy.get("cusconfig.report.reportPath") + "/file/金元小助播报模板.docx";


        String uploadresult = "";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String date = simpleDateFormat.format(new Date());
        if (type.equals("日报")) {
            map.put("type", "-" + type);
            File file = new File(templateFile);
            pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
        }

        if (type.equals("周报")) {
            map.put("type", "-" + type);
            map.put("今日", "本周");
            File file = new File(templateFile);
            pdf = "/data/shequ/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
        }

        if (type.equals("月报")) {
            map.put("type", "-" + type);
            map.put("今日", "本月");
            File file = new File(templateFile);
            pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
        }

        if (type.equals("")) {
            map.put("type", type);
            map.put("今日", "");
            File file = new File(templateFile);
            pdf = propertiesProxy.get("cusconfig.report.reportPath") + "/file/pdf/" + date + file.getName().replace("模板.docx", "") + type + ".pdf";
        }
        // 模板文件
        String filename = UUID.randomUUID().toString();
        String outPath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/word/" + filename + ".docx";
        try {
            String templateFilePath = propertiesProxy.get("cusconfig.report.reportPath") + "/file/金元小助播报模板.docx";
            InputStream is1 = new FileInputStream(templateFilePath);
            InputStream is2 = new FileInputStream(templateFilePath);
            // 用来替换变量
            XWPFDocument hdt = new XWPFDocument(is1);
            // 用来输出原格式
            XWPFDocument hdt1 = new XWPFDocument(is2);

            //查询今日通话数量
            Cnd connectNumCnd = Cnd.NEW();
            connectNumCnd.and("customer_name", "=", SecurityUtil.getUserUsername());
            connectNumCnd.and("connect_time", "between", new Object[]{startTime, endTime});
            int connectNum = sqfwServicerecordForAdminService.count(connectNumCnd);

            map.put("name", SecurityUtil.getUserUsername());
            map.put("time", startTime + "——" + endTime);
            map.put("callnumber", String.valueOf(connectNum));

            //查询今日完成条数
            DecimalFormat df = new DecimalFormat("#.00");

            Cnd finishNumCnd = Cnd.NEW();
            finishNumCnd.and("customer_name", "=", SecurityUtil.getUserUsername());
            finishNumCnd.and("handle_result", "=", "完成");
            finishNumCnd.and("connect_time", "between", new Object[]{startTime, endTime});
            List<Sqfw_servicerecord> finishNum = sqfwServicerecordForAdminService.query(finishNumCnd);
            map.put("finishnumber", String.valueOf(finishNum.size()));
            if (connectNum == 0) {
                map.put("percentage", "0");
            } else {
                double percent = ((double) finishNum.size() / (double) connectNum) * 100;
                map.put("percentage", df.format(percent) + "%");
            }

            //计算平均完成时长
            double timeall = 0L;
            for (int i = 0; i < finishNum.size(); i++) {
                Long timelag = finishNum.get(i).getFinish_time().getTime() - finishNum.get(i).getReceive_time().getTime();
                double hour = timelag / 1000 * 0.0002777;
                timeall += hour;
            }
            if (finishNum.size() == 0) {
                map.put("avg", 0 + "小时");
            } else {
                map.put("avg", df.format(timeall / finishNum.size()) + "小时");
            }

            // TestPoi cc = new TestPoi();
            // 替换变量
            replaceText(hdt, map);
            // 替换成原格式
            setStyle(hdt1, hdt);

            // 输出文件
            OutputStream os = new FileOutputStream(outPath);
            hdt.write(os);
            hdt.close();
            hdt1.close();

            Word2PdfJacobUtil2(outPath, pdf);

            SysOss uploadOSS = sysOssService.upload(FileUtil.file(pdf));
            uploadresult = uploadOSS.getUrl();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        result.addData(uploadresult);
        return result;
    }


    public static void Word2PdfJacobUtil2(String inPath, String outPath) throws IOException {
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;

        try {
            fileInputStream = new FileInputStream(inPath);
            XWPFDocument xwpfDocument = new XWPFDocument(fileInputStream);
            PdfOptions pdfOptions = PdfOptions.create();
            fileOutputStream = new FileOutputStream(outPath);
            PdfConverter.getInstance().convert(xwpfDocument, fileOutputStream, pdfOptions);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fileInputStream) {
                    fileInputStream.close();
                }
                if (null != fileOutputStream) {
                    fileOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    public static void Word2PdfJacobUtil(String inPath, String outPath) throws IOException {

        InputStream docxInputStream = null;
        OutputStream outputStream = null;
        try {
            // 原word地址
            docxInputStream = new FileInputStream(inPath);
            // 转换后pdf生成地址
            outputStream = new FileOutputStream(outPath);
            IConverter converter = LocalConverter.builder().build();
            converter.convert(docxInputStream)
                    .as(DocumentType.DOCX)
                    .to(outputStream)
                    .as(DocumentType.PDF).execute();
            // 关闭
            converter.shutDown();
            // 关闭
            outputStream.close();
            // 关闭
            docxInputStream.close();
        } catch (Exception e) {
            System.out.println("[documents4J] word转pdf失败:" + e.toString());
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (docxInputStream != null) {
                docxInputStream.close();
            }
        }


    }


    /**
     * 替换文档中的参数（word）
     *
     * @param doc
     * @param params
     */
    private static void replaceText(XWPFDocument doc, Map<String, String> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while (iterator.hasNext()) {
            para = iterator.next();
            replaceInPara(para, params);
        }
    }

    /**
     * 替换段落中的参数（word）
     *
     * @param para
     * @param params
     */
    private static void replaceInPara(XWPFParagraph para, Map<String, String> params) {
        List<XWPFRun> runs = para.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            XWPFRun run = runs.get(i);
            String runText = run.toString();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                if (runText.contains(entry.getKey())) {
                    para.removeRun(i);
                    // 重新插入run里内容格式可能与原来模板的格式不一致
                    para.insertNewRun(i).setText(runText.replace(entry.getKey(), entry.getValue()));
                }
            }
        }
    }

    /**
     * 处理文档替换内容的格式问题（word）
     *
     * @param tempDoc
     * @param doc
     */
    private static void setStyle(XWPFDocument tempDoc, XWPFDocument doc) {
        Iterator<XWPFParagraph> iterator = tempDoc.getParagraphsIterator();
        Iterator<XWPFParagraph> iterator2 = doc.getParagraphsIterator();
        XWPFParagraph para;
        XWPFParagraph para2;
        while (iterator.hasNext() && iterator2.hasNext()) {
            para = iterator.next();
            para2 = iterator2.next();
            setStyleInPara(para, para2);
        }
    }

    /**
     * 处理段落替换内容的格式问题（word）
     *
     * @param para
     * @param para2
     */
    private static void setStyleInPara(XWPFParagraph para, XWPFParagraph para2) {
        List<XWPFRun> runs = para.getRuns();
        List<XWPFRun> runs2 = para2.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            XWPFRun run = runs.get(i);
            XWPFRun run2 = runs2.get(i);
            run2.getCTR().setRPr(run.getCTR().getRPr());
        }
    }

    @At("/listByServiceOrderIdList")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据serviceOrderId查询数据")
    @ApiFormParams(implementation = List.class)
    @ApiResponses
    @SLog(tag = "根据服务记录id查询数据")
    public Result<List<UserServiceOrderVO>> listByServiceOrderIdList(@Param("serviceOrderIdList") List<String> serviceOrderIdList) {
        List<UserServiceOrderVO> resultList = sqfwServicerecordForAdminService.listByServiceOrderIdList(serviceOrderIdList);
        return Result.success(resultList);
    }

    @At("/getServiceOrderDetail")
    @Ok("json")
    @POST
    @ApiOperation(name = "获取通讯服务记录")
    @ApiFormParams(
            {
                    @ApiFormParam(name = "serviceOrderId", description = "唯一标识", required = true, check = true),
                    @ApiFormParam(name = "userId", description = "用户id", required = true, check = true),
            }
    )
    @SLog(tag = "根据服务记录id获取通讯服务记录", value = "${args[0]},${args[1]},${args[2]}")
    public Result<UserServiceOrderVO> getServiceOrderDetail(@Param("serviceOrderId") String serviceOrderId, @Param("userId") String userId, @Param("recordType") String recordType) {
        if (StringUtils.isBlank(serviceOrderId)) return Result.error("id不能为空");
        // 使用id查serviceOder
        Sqfw_servicerecord serviceRecord = sqfwServicerecordForAdminService.fetch(serviceOrderId);

        if (serviceRecord == null) return Result.error("语音服务记录为空");

        // wzy 2023-5-19 需要对通话记录中的内容
        if (StringUtils.isNotBlank(serviceRecord.getRecording_text())) {
            serviceRecord.setRecording_text(AudioToTextUtils.replaceMsgContent(serviceRecord.getRecording_text()));
        }
        UserServiceOrderVO resultVO = new UserServiceOrderVO();
        BeanUtil.copyProperties(serviceRecord, resultVO);

        if (StringUtils.isNotBlank(recordType) && recordType.equals("cc")) userId = serviceRecord.getCreatedBy();
        List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceOrderId).and("user_id", "=", userId));
        List<SqfwWorkOrderVO> userVOList = sqfwWorkorderService.getVO(workOrderList);
        if (workOrderList.size() > 0) {
            resultVO.setUserWorkOrder(userVOList.get(0));
        }

        // 根据sqfw_id 和 from_userid 查询相应的工单信息
        List<Sqfw_workorder> userWorkOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId())
                .and("from_user_id", "=", serviceRecord.getCreatedBy()));
        List<SqfwWorkOrderVO> otherUserVOList = sqfwWorkorderService.getVO(userWorkOrderList);
        resultVO.setUserWorkOrderList(otherUserVOList);
        // 使用id和userId查workOrder
        return Result.success(resultVO);
    }

    @At("/deleteServiceOrderLogic")
    @Ok("json")
    @POST
    @ApiOperation(name = "删除录音服务记录")
    @SLog(tag = "删除录音服务记录,工作记录", value = "${args[0]}")
    @ApiFormParams(@ApiFormParam(name = "serviceOrderId", description = "唯一标识", required = true, check = true))
    public Result<Integer> deleteServiceOrderLogic(@Param("serviceOrderId") String serviceOrderId) {
        Integer deleteCount = sqfwServicerecordForAdminService.deleteServiceOrderLogic(serviceOrderId);
        if (deleteCount == null || deleteCount == 0) return Result.error("删除失败");
        return Result.success(deleteCount);
    }

    @At("/listServiceRecord")
    @Ok("json")
    @POST
    @ApiOperation(name = "分页查询通讯服务记录")
    @ApiFormParams(
            value = {
                    @ApiFormParam(name = "pageNo", example = "1", description = "页码", type = "integer"),
                    @ApiFormParam(name = "pageSize", example = "10", description = "页大小", type = "integer"),
                    @ApiFormParam(name = "pageOrderName", example = "createdAt", description = "排序字段"),
                    @ApiFormParam(name = "pageOrderBy", example = "descending", description = "排序方式")
            },
            implementation = Sqfw_servicerecord.class
    )
    @ApiResponses(
            implementation = Sqfw_servicerecord.class
    )
    @SLog(tag = "分页查询通讯服务记录")
    public Result<?> listServiceRecord(@Param("..") Sqfw_servicerecord bean,
                                       @Param("pageNo") int pageNo,
                                       @Param("pageSize") int pageSize,
                                       @Param("pageOrderName") String pageOrderName,
                                       @Param("pageOrderBy") String pageOrderBy) {

        String userId = SecurityUtil.getUserId();
        List<String> roleList = sysUserService.getRoleList(userId);
        Set<String> roleSet = Sets.newHashSet(roleList);

        Pagination pagination = sqfwServicerecordForAdminService.listServiceRecordNew(bean, pageNo, pageSize, roleSet, userId);
        return Result.success(pagination);
    }

    @At("/doUpdateData")
    @Ok("json")
    @GET
    public Result<?> doUpdateData() {
        List<Sqfw_servicerecord> serviceRecordList = sqfwServicerecordForAdminService.query(Cnd.where("delflag", "=", false));
        for (Sqfw_servicerecord serviceRecord : serviceRecordList) {
            List<Sqfw_workorder> workOrderList = sqfwWorkorderService.query(Cnd.where("sqfw_id", "=", serviceRecord.getId()).and("delflag", "=", false));

            List<Sqfw_workorder> otherUserWorkOrderList = Lists.newArrayList();
            Sqfw_workorder workOrderOfServiceRecord = null;
            for (Sqfw_workorder workOrder : workOrderList) {
                if (workOrder.getUser_id().equals(serviceRecord.getCreatedBy())) workOrderOfServiceRecord = workOrder;
                else otherUserWorkOrderList.add(workOrder);
            }

            Set<String> sendUserIdSet = otherUserWorkOrderList.stream().map(Sqfw_workorder::getUser_id).collect(Collectors.toSet());

            List<Sys_user> sendUserList = sysUserService.query(Cnd.where("id", "in", sendUserIdSet));

            List<String> userNameList = Lists.newArrayList();
            List<String> userPhoneList = Lists.newArrayList();
            for (Sys_user sysUser : sendUserList) {
                userNameList.add(sysUser.getUsername());
                userPhoneList.add(sysUser.getLoginname());
            }

            String serviceName = Joiner.on(",").join(userNameList);
            String servicePhone = Joiner.on(",").join(userPhoneList);

            serviceRecord.setService_name(serviceName);
            serviceRecord.setService_phone(servicePhone);

            if (workOrderOfServiceRecord != null) {
                serviceRecord.setFinish_time(workOrderOfServiceRecord.getComplete_time());
                serviceRecord.setFinishStatus(workOrderOfServiceRecord.getWk_status());
            }

            sqfwWorkorderService.update(serviceRecord);
        }

        return Result.success();
    }

    @At("/listAllServiceOrderType")
    @Ok("json")
    @GET
    public Result<List<String>> listAllServiceOrderType(@Param("unitId") String unitId) {
        List<String> list = sqfwServicerecordForAdminService.listAllServiceOrderType(unitId);
        return Result.success(list);
    }


    private Cnd createListServiceRecordPermissionCnd(String userId) {

        List<String> roleList = sysUserService.getRoleList(userId);
        Set<String> roleSet = Sets.newHashSet(roleList);

        Cnd cnd = Cnd.NEW();

        boolean superAdminFlag = false;
        boolean adminFlag = false;

        if (roleSet.contains("superadmin") || roleSet.contains("sysadmin")) superAdminFlag = true;
        if (roleSet.contains("admin")) adminFlag = true;

        if (!superAdminFlag && !adminFlag) {
            Sys_user sysUser = sysUserService.fetch(userId);
            SqlExpressionGroup e1 = Cnd.exps("customer_phone", "=", sysUser.getLoginname());
            SqlExpressionGroup e2 = Cnd.exps("service_phone", "like", "%" + sysUser.getLoginname() + "%");
            SqlExpressionGroup e3 = Cnd.exps("copy_phone", "like", "%" + sysUser.getLoginname() + "%");

            cnd.and(e1.or(e2).or(e3));
        }

        if (!superAdminFlag && adminFlag) {
            // 如果只是普通的管理员 首先查出这个公司中所有的员工
            Sys_user sysUser = sysUserService.fetch(userId);
            String unitId = sysUser.getUnitId();
            List<Sys_user> userList = sysUserService.query(Cnd.where("unitid", "=", unitId));
            Set<String> userPhoneSet = userList.stream().map(Sys_user::getLoginname).collect(Collectors.toSet());
            SqlExpressionGroup e = Cnd.exps("customer_phone", "like", "%" + sysUser.getLoginname() + "%");
            for (String userPhone : userPhoneSet) {
                SqlExpressionGroup e1 = Cnd.exps("customer_phone", "like", "%" + userPhone + "%");
                e.or(e1);
            }
            cnd.and(e);
        }

        return cnd;
    }

    // 获取任务记录条件
    private Cnd getConditionList(SqfwServicerecordForAdminDTO bean) {
        Cnd cnd = Cnd.NEW();

        if (Strings.isNotBlank(bean.getQueryAll())) {
            String queryAll = bean.getQueryAll();
            SqlExpressionGroup e1 = Cnd.exps("community", "like", "%" + queryAll + "%");
            SqlExpressionGroup e2 = Cnd.exps("customer_name", "like", "%" + queryAll + "%");
            SqlExpressionGroup e3 = Cnd.exps("finish_status", "like", "%" + queryAll + "%");
            SqlExpressionGroup e4 = Cnd.exps("duration", "like", "%" + queryAll + "%");
            SqlExpressionGroup e5 = Cnd.exps("customer_phone", "like", "%" + queryAll + "%");
            SqlExpressionGroup e6 = Cnd.exps("customer_address", "like", "%" + queryAll + "%");
            SqlExpressionGroup e7 = Cnd.exps("recording_file", "like", "%" + queryAll + "%");
            SqlExpressionGroup e8 = Cnd.exps("type", "like", "%" + queryAll + "%");
            SqlExpressionGroup e9 = Cnd.exps("createdby", "like", "%" + queryAll + "%");
            SqlExpressionGroup e10 = Cnd.exps("service_name", "like", "%" + queryAll + "%");
            cnd.and(e1.or(e2).or(e3).or(e4).or(e5).or(e6).or(e7).or(e8).or(e9).or(e10));
        }
        if (Strings.isNotBlank(bean.getProvince())) {
            cnd.and(Sqfw_formSummary::getProvince, "=", bean.getProvince());
        }
        if (Strings.isNotBlank(bean.getCity())) {
            cnd.and(Sqfw_formSummary::getCity, "=", bean.getCity());
        }
        if (Strings.isNotBlank(bean.getDistrict())) {
            cnd.and(Sqfw_formSummary::getDistrict, "=", bean.getDistrict());
        }
        if (Strings.isNotBlank(bean.getCounty())) {
            cnd.and(Sqfw_formSummary::getCounty, "=", bean.getCounty());
        }
        if (Strings.isNotBlank(bean.getCommunity())) {
            cnd.and(Sqfw_formSummary::getCommunity, "=", bean.getCommunity());
        }

        if (bean.getCustomer_name() != null && Strings.isNotBlank(bean.getCustomer_name().toString())) {
            cnd.and("customer_name", "like", "%" + bean.getCustomer_name() + "%");
        }

        if (bean.getFinishStatus() != null && Strings.isNotBlank(bean.getFinishStatus().toString())) {
            cnd.and("finish_status", "like", "%" + bean.getFinishStatus() + "%");
        }

        if (bean.getDuration() != null && Strings.isNotBlank(bean.getDuration().toString())) {
            cnd.and("duration", "like", "%" + bean.getDuration() + "%");
        }

        if (bean.getCustomer_phone() != null && Strings.isNotBlank(bean.getCustomer_phone().toString())) {
            cnd.and("customer_phone", "like", "%" + bean.getCustomer_phone() + "%");
        }

        if (bean.getCustomer_address() != null && Strings.isNotBlank(bean.getCustomer_address().toString())) {
            cnd.and("customer_address", "like", "%" + bean.getCustomer_address() + "%");
        }

        if (bean.getRecording_file() != null && Strings.isNotBlank(bean.getRecording_file().toString())) {
            cnd.and("recording_file", "like", "%" + bean.getRecording_file() + "%");
        }

        if (bean.getRecording_text() != null && Strings.isNotBlank(bean.getRecording_text().toString())) {
            cnd.and("recording_text", "like", "%" + bean.getRecording_text() + "%");
        }

        if (bean.getType() != null && Strings.isNotBlank(bean.getType().toString())) {
            cnd.and("type", "=", bean.getType());
        }

        if (bean.getCustomer_need() != null && Strings.isNotBlank(bean.getCustomer_need().toString())) {
            cnd.and("customer_need", "like", "%" + bean.getCustomer_need() + "%");
        }

        if (bean.getService_name() != null && Strings.isNotBlank(bean.getService_name().toString())) {
            cnd.and("service_name", "like", "%" + bean.getService_name() + "%");
        }

        if (bean.getService_phone() != null && Strings.isNotBlank(bean.getService_phone().toString())) {
            cnd.and("service_phone", "like", "%" + bean.getService_phone() + "%");
        }

        if (bean.getQueryTime() != null && Strings.isNotBlank(bean.getQueryTime())) {
            String time[] = bean.getQueryTime().split(",");
            cnd.and("createdat", "between", new Object[]{Long.valueOf(time[0]), Long.valueOf(time[1])});
        }

        if (bean.getHandle_result() != null && Strings.isNotBlank(bean.getHandle_result().toString())) {
            cnd.and("handle_result", "=", "%" + bean.getHandle_result() + "%");
        }

        if (bean.getHandle_detail() != null && Strings.isNotBlank(bean.getHandle_detail().toString())) {
            cnd.and("handle_detail", "like", "%" + bean.getHandle_detail() + "%");
        }

        if (bean.getCopyName() != null && Strings.isNotBlank(bean.getCopyName().toString())) {
            cnd.and("copy_name", "like", "%" + bean.getCopyName() + "%");
        }

        if (bean.getCopyPhone() != null && Strings.isNotBlank(bean.getCopyPhone().toString())) {
            cnd.and("copy_phone", "like", "%" + bean.getCopyPhone() + "%");
        }

        if (bean.getCompanyName() != null && Strings.isNotBlank(bean.getCompanyName().toString())) {
            cnd.and("company_name", "like", "%" + bean.getCompanyName() + "%");
        }

        if (bean.getCreatedBy() != null && Strings.isNotBlank(bean.getCreatedBy())) {
            cnd.and("createdby", "=", bean.getCreatedBy());
        }

        cnd.and("delflag", "=", false);

        return cnd;
    }


    /*
     * 根据条件下载pdf集合（用于后台管理系统）
     * Add by LJT 2023-11-02
     */
    @At("/generateServiceRecordPdfCollByCond")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成pdf合集")
    @ApiFormParams(
            implementation = SqfwServicerecordForAdminDTO.class
    )
    @SLog(tag = "根据服务记录id数组生成pdf合集zip", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordPdfCollByCond(@Param("..") SqfwServicerecordForAdminDTO bean) {
        Cnd cnd = this.getConditionList(bean);
        List<ServiceRecordPdfOrExcelCollDTO> recordList = sqfwServicerecordForAdminService.getRecordList(cnd);
        if (recordList.size() <= 0) {
            return Result.error("无符合条件数据！");
        }
        String pdfUrl = sqfwFormSummaryService.generateServiceRecordPdfColl(recordList, null);
        if (null == pdfUrl) {
            return Result.error("未查询到符合条件数据生成pdf文件！");
        }
        return Result.data(pdfUrl);
    }

    /*
     * 根据条件下载excel集合（用于后台管理系统）
     * Add by LJT 2023-11-02
     */
    @At("/generateServiceRecordExcelCollByCond")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id和汇总Id数组生成Excel合集")
    @ApiFormParams(
            implementation = SqfwServicerecordForAdminDTO.class
    )
    @SLog(tag = "根据服务记录id数组和汇总Id生成Excel合集", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelCollByCond(@Param("..") SqfwServicerecordForAdminDTO bean, @Param("fileIndexList") List<Integer> fileIndex, @Param("excelType") String excelType) {
        Cnd cnd = this.getConditionList(bean);
        List<ServiceRecordPdfOrExcelCollDTO> recordList = sqfwServicerecordForAdminService.getRecordList(cnd);
        if (recordList.size() <= 0) {
            return Result.error("无符合条件数据！");
        }
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwSummaryForAdminService.generateServiceRecordExcelCollZipForBM(bean.getCounty(), recordList, userId, fileIndex, excelType);
        if (null == excelUrl) {
            return Result.error("未查询到符合条件数据生成Excel文件！");
        }
        return Result.data(excelUrl);
    }

    /*
     * 勾选下载excel集合（用于后台管理系统）
     * Add by LJT 2023-11-02
     */
    @At("/generateServiceRecordPdfColl")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成pdf合集")
    @SLog(tag = "根据服务记录id数组生成pdf合集", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordPdfColl(@Param("conditionList") List<ServiceRecordPdfOrExcelCollDTO> conditionList) {
        String pdfUrl = sqfwFormSummaryService.generateServiceRecordPdfColl(conditionList, null);
        return Result.data(pdfUrl);
    }

    /*
     * 勾选下载excel集合（用于后台管理系统）
     * Add by LJT 2023-11-02
     */
    @At("/generateServiceRecordExcelColl")
    @Ok("json")
    @POST
    @ApiOperation(name = "根据服务记录id数组生成Excel合集")
    @SLog(tag = "根据服务记录id数组生成Excel合集", value = "${args[0]}")
    @SaCheckLogin
    public Result<?> generateServiceRecordExcelColl(@Param("conditionList") List<ServiceRecordPdfOrExcelCollDTO> conditionList, @Param("fileIndex") Integer fileIndex, @Param("excelType") String excelType) {
        String userId = SecurityUtil.getUserId();
        String excelUrl = sqfwFormSummaryService.generateServiceRecordExcelColl(conditionList, userId, fileIndex, excelType);
        return Result.data(excelUrl);
    }

}
